﻿/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

const baseURL = 'http://172.26.200.203:55888';

// 日期格式化
function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time.replace(new RegExp(/-/gm), "/");
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}
// 表单重置
function resetForm(refName, self) {
  if (self.$refs[refName]) {
    self.$refs[refName].resetFields();
  }
}

// 添加日期范围
function addDateRange(params, dateRange) {
  var search = params;
  search.beginTime = "";
  search.endTime = "";
  if (null != dateRange && "" != dateRange) {
    search.beginTime = dateRange[0];
    search.endTime = dateRange[1];
  }
  return search;
}
// 取映射集合中的数值
function selectLabelName(datas, value) {
  // 取对应的键值
  var valTemp = datas[value];
  var val = undefined === valTemp ? "" : valTemp;
  return val;
}

// 回显数据字典
function selectDictLabelEdit(datas, value) {
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].projectTypeId == "" + value) {
      actions.push(datas[key].projectTypeName);
      return true;
    }
  });
  return actions.join("");
}
// 回显数据字典
function selectDictLabel(datas, value) {
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].dictValue == "" + value) {
      actions.push(datas[key].dictLabel);
      return true;
    }
  });
  return actions.join("");
}

// 回显数据字典（字符串数组）
function selectDictLabels(datas, value, separator) {
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue == "" + temp[val]) {
        actions.push(datas[key].dictLabel + currentSeparator);
      }
    });
  });
  return actions.join("").substring(0, actions.join("").length - 1);
}

// 通用下载方法
function download(fileName) {
  window.location.href =
      baseURL +
      "/common/download?fileName=" +
      encodeURI(fileName) +
      "&delete=" +
      true;
}
// 通用下载方法
function downloadParams(fileName, del) {
  window.location.href =
      baseURL +
      "/common/download?fileName=" +
      encodeURI(fileName) +
      "&delete=" +
      del;
}

// 下载TCC设计方案
function downLoadProgramme(programmeId, downLoadType, template, fileId) {
  window.location.href =
      baseURL +
      "/common/downloadProgrammeFile?programmeId=" +
      programmeId +
      "&downLoadType=" +
      downLoadType +
      "&template=" +
      template +
      "&fileId=" +
      fileId;
}

// 统一文件文件下载操作
// id: 操作记录标识id   projectId:项目标识   typeId:模块类型标识
// 第一种方式 id有值   projectId与typeId为空  从操作记录中下载文件
// 第二种方式 id无值=null   projectId与typeId有值，从表格页面点击对应模块下载最新上传文件的方式
function unifiedDownLoad(id, projectId, typeId) {
  window.location.href =
      baseURL +
      "/import/operation/unifiedDownLoad?projectId=" +
      projectId +
      "&id=" +
      id +
      "&typeId=" +
      typeId;
}

// 字符串格式化(%s )
function sprintf(str) {
  var args = arguments,
      flag = true,
      i = 1;
  str = str.replace(/%s/g, function () {
    var arg = args[i++];
    if (typeof arg === "undefined") {
      flag = false;
      return "";
    }
    return arg;
  });
  return flag ? str : "";
}

// 转换字符串，undefined,null等转化为""
function praseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
function handleTree(data, id, parentId, children, rootId) {
  id = id || "id";
  parentId = parentId || "parentId";
  children = children || "children";
  rootId =
      rootId ||
      Math.min.apply(
          Math,
          data.map((item) => {
            return item[parentId];
          })
      ) ||
      0;
  //对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data));
  //循环所有项
  const treeData = cloneData.filter((father) => {
    let branchArr = cloneData.filter((child) => {
      //返回每一项的子级数组
      return father[id] === child[parentId];
    });
    branchArr.length > 0 ? (father.children = branchArr) : "";
    //返回第一层
    return father[parentId] === rootId;
  });
  return treeData != "" ? treeData : data;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
function tansParams(params) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && typeof value[key] !== "undefined") {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

// 获取当前周
function getWeek(dt) {
  // 默认当前时间
  var d = dt ? new Date(dt) : new Date();
  var day = d.getDay();
  var originDate = d.getFullYear() + '/' + "01" + '/' + "01" + ' 00:00:00';
  var nowDate = d.getFullYear() + '/' + ((d.getMonth() + 1) > 9 ? (d.getMonth() + 1) : '0' + (d.getMonth() + 1)) + "/" + (d.getDate() > 9 ? d.getDate() : '0' + d.getDate()) + ' 00:00:00';
  var nowStrapTime = (new Date(nowDate)).getTime();
  var originStrapTime = (new Date(originDate)).getTime();
  var originDay = ((new Date(originStrapTime)).getDay()) == 0 ? 7 : ((new Date(originStrapTime)).getDay());
  var nowDay = d.getDay() == 0 ? 7 : d.getDay();
  var weeks = 0;
  var resultStrap = 0;
  if (nowDay > originDay) {
    resultStrap = nowStrapTime - (nowDay - originDay) * 1000 * 3600 * 24 - originStrapTime;
    if (resultStrap > 0) {
      weeks = (resultStrap / (3600 * 1000 * 24 * 7)) + 1
    } else {
      weeks = 1
    }
  } else {
    resultStrap = nowStrapTime + (originDay - nowDay) * 1000 * 3600 * 24 - originStrapTime;
    weeks = (resultStrap / (3600 * 1000 * 24 * 7)) + 1
  }
  return weeks
}

/**
 * 
 * @param {*} type year month day time obj
 * @returns 
 */
function getDateTime(type, val, hg) {
  var date = new Date();
  if (val) {
    date = new Date(val)
  }
  var hengGang = "-";
  if (Object.prototype.toString.call(hg) == "[object Boolean]") {
    if (!hg) {
      hengGang = ''
    }
  } else {
    if (hg) {
      hengGang = hg
    }
  }
  var maoHao = ":";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var curDate = date.getDate();
  var curHours = date.getHours().toString();
  var curMinutes = date.getMinutes().toString();
  var curSeconds = date.getSeconds().toString();

  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (curDate >= 0 && curDate <= 9) {
    curDate = "0" + curDate;
  }
  if (curHours >= 0 && curHours <= 9) {
    curHours = "0" + curHours;
  }
  if (curMinutes >= 0 && curMinutes <= 9) {
    curMinutes = "0" + curMinutes;
  }
  if (curSeconds >= 0 && curSeconds <= 9) {
    curSeconds = "0" + curSeconds;
  }
  var currentdate = "";
  if (type == "year") {
    currentdate = year;
    return currentdate;
  } else if (type == "month") {
    currentdate = year + hengGang + month;
    return currentdate;
  } else if (type == "day") {
    currentdate = year + hengGang + month + hengGang + curDate;
    return currentdate;
  } else if (type == "hours") {
    currentdate = year + hengGang + month + hengGang + curDate + " " + curHours;
    return currentdate;
  } else if (type == "hours") {
    currentdate = year + hengGang + month + hengGang + curDate + " " + curHours;
    return currentdate;
  } else if (type == "minutes") {
    currentdate = year + hengGang + month + hengGang + curDate + " " + curHours + maoHao + curMinutes;
    return currentdate;
  } else if (type == "obj") {
    return {
      year, month, curDate, curHours, curMinutes, curSeconds
    };
  } else {
    currentdate = year + hengGang + month + hengGang + curDate + " " + curHours + maoHao + curMinutes + maoHao + curSeconds;
    return currentdate;
  }
}
